package com.mystore.console.controller;

import com.mystore.common.utils.file.FileUpDownUtils;
import com.mystore.framework.pojo.App;
import com.mystore.framework.pojo.FileModel;
import com.mystore.framework.service.impl.IAppServiceImpl;
import com.mystore.framework.service.impl.IFileModelServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("console/file")
public class FileDownLoadController {
    /**
     * 服务对象
     */
    @Resource
    private IFileModelServiceImpl iFileModelServiceImpl;
    @Resource
    private IAppServiceImpl iAppServiceImpl;
    @GetMapping("/download.do")
    public void download(int fileModelId, HttpServletRequest request,HttpServletResponse response, int appId) throws ServletException, IOException {
        FileModel fileModel=iFileModelServiceImpl.selectById(fileModelId);
        try {
            App app=iAppServiceImpl.selectById(appId);
            app.setDownloadCount(app.getDownloadCount()+1);
            iAppServiceImpl.updateOne(app);
            FileUpDownUtils.download(fileModel.getFileModelPath(), response);
        } catch (IOException e) {
            request.getRequestDispatcher("/notFoundResource.do").forward(request,response);
        }
    }
    @GetMapping("/image.do")
    public void image(int fileModelId, HttpServletResponse response){
        FileModel fileModel=iFileModelServiceImpl.selectById(fileModelId);
        try {
            FileUpDownUtils.loadImage(fileModel.getFileModelPath(), response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
